const express = require('express');
const cheerio = require('cheerio');
const axios = require('axios');
const app = express();

app.get('/search', async (req, res) => {
  const keyword = req.query.keyword || '';
  // const sortBy = req.query.sortBy || 'viewCount' // 默认按照阅读量排序
  const page = parseInt(req.query.page) || 1;
  const pageSize = 10;

  try {
    const response = await axios.get(
      // eslint-disable-next-line no-undef
      `https://juejin.cn/search?query=${encodeURIComponent(keyword)}&sort=${sortBy}&page=${page}`
    );

    const $ = cheerio.load(response.data);
    const articles = [];

    $('.content-box .info-box').each((index, element) => {
      const title = $(element).find('.title').text().trim();
      const link = $(element).find('.title').attr('href');
      const viewCount = parseInt($(element).find('.meta-list .iconfont-like').next().text().trim());
      const likeCount = parseInt($(element).find('.meta-list .iconfont-like').text().trim());
      const collectCount = parseInt(
        $(element).find('.meta-list .iconfont-collection').text().trim()
      );

      articles.push({
        title,
        link,
        viewCount,
        likeCount,
        collectCount
      });
    });

    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedArticles = articles.slice(startIndex, endIndex);

    res.json(paginatedArticles);
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'An error occurred' });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
